package com.geekcoding.geekoj.service;

import com.geekcoding.common.exceptions.GeekRuntimeException;
import com.geekcoding.geekoj.config.WebContextHolder;
import com.geekcoding.geekoj.entity.UserEntity;
import com.geekcoding.geekoj.nums.Role;
import com.geekcoding.geekoj.nums.WebContextKey;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {

    public UserEntity currentUser() {
        return WebContextHolder.get(WebContextKey.CURRENT_USER);
    }

    public void checkAdminUser() {
        UserEntity userEntity = currentUser();
        Optional.ofNullable(userEntity.getRole()).filter(role -> role.equals(Role.ADMIN)).orElseThrow(() -> new GeekRuntimeException("暂无权限！"));
    }

    public void checkUser(String userId) {
        Optional.ofNullable(currentUser()).filter(userEntity -> userEntity.getId().equals(userId)).orElseThrow(() -> new GeekRuntimeException("暂无权限！"));
    }
}
